import platform
import re
import os
import ctypes
import time
import datetime
import math


def system_get_platform_info():
    sysplatform = platform.system().lower().strip()
    python_bit = platform.architecture()[0]
    python_bit_num = re.findall('(\d+)\w*', python_bit)[0]
    return sysplatform, python_bit_num


sys_platform, python_bit_num = system_get_platform_info()
system_type = sys_platform + python_bit_num
usNetSdk_lib = 0


if sys_platform == 'linux':
    CB_FUNCTYPE = ctypes.CFUNCTYPE
elif sys_platform == 'windows':
    CB_FUNCTYPE = ctypes.WINFUNCTYPE
else:
    print("************不支持的平台**************")
    # exit(0)


def _load_lib(libpath):
    # try:
    #     if sys_platform == "linux":
    #         msg_lib_path = os.path.join(*(os.path.split(__file__)[:-1] + (libpath,)))
    #         return ctypes.cdll.LoadLibrary(msg_lib_path)
    #     elif sys_platform == "windows":
    #         msg_lib_path = os.path.join(*(os.path.split(__file__)[:-1] + (libpath,)))
    #         # print("###### assis lib: %s" % msg_lib_path)
    #         return ctypes.windll.LoadLibrary(libpath)
    # except Exception as ex:
    #     print("库：%s 加载错误。Error： %s" % (libpath, ex))
    # return None
    libhandle = None
    try:
        if sys_platform == "linux":
            msg_lib_path = os.path.join(*(os.path.split(__file__)[:-1] + (libpath,)))
            libhandle = ctypes.cdll.LoadLibrary(libpath)
        elif sys_platform == "windows":
            msg_lib_path = os.path.join(*(os.path.split(__file__)[:-1] + (libpath,)))
            # print("###### assis lib: %s" % msg_lib_path)
            libhandle = ctypes.windll.LoadLibrary(libpath)
    except Exception as ex:
        print("库：%s 加载错误。Error： %s" % (libpath, ex))
        return None
    else:
        return libhandle



_Base_config_lib = _load_lib("base_comm_config.dll")
# const char* WINAPI replace_dir(const char* path, char* outPath)
_replace_dir = _Base_config_lib.replace_dir
_replace_dir.argtypes = (ctypes.c_char_p, ctypes.c_char_p)
_replace_dir.restype = ctypes.c_char_p


# 获取中心服务地址，及端口信息
# bool WINAPI get_ipaddress(const char* type, char* address, char* port);
c_get_ipaddress = _Base_config_lib.get_ipaddress
c_get_ipaddress.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)
c_get_ipaddress.restype = ctypes.c_bool

# 操作配置文件（ini):  获取（GetIniString）和设置(SetIniString) 配置文件信息
# 参数：
#    1、file (ini文件全名，支持部分环境变量）
#    2、appName ( [appName] ）
#    3、appName ( [appName] ）
#    4、key     ( key =  ）
#    5、Default ( 缺省时的值）
#    6、buffer ( 输入/输出数据）
#    7、leng ( 数据尺寸）
#int WINAPI GetIniString(const char* file, const char* appName, const char* key, const char* Default, char *buffer, int leng);
c_get_inistring = _Base_config_lib.GetIniString
c_get_inistring.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int)
c_get_inistring.restype = ctypes.c_int


#BOOL WINAPI SetIniString(const char* file, const char* appName, const char* key, const char *buffer );
c_set_inistring = _Base_config_lib.SetIniString
c_set_inistring.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p)
c_set_inistring.restype = ctypes.c_bool


def getIniString(file, appname, key):
    # byteFile = str(file).encode('utf-8')
    # byteAppname = str(appname).encode('utf-8')
    # byteKey = str(key).encode('utf-8')
    buffer = ctypes.create_string_buffer(1024)
    res = c_get_inistring(file, appname, key, b'', buffer, 1024)
    print("get_inistring result: ", res)
    return res, buffer.value.decode('utf-8')

# install\\; system32\\; DRIVERS\\; ROOT\\;  WINDOWS\\;  
# 如获取安装目录的 Pthon 目录：“install\\pthon_dir\\”
def ReplaceDirector(inPath):
    read_buff = (ctypes.c_char * (260) )()
    _replace_dir(str(inPath).encode("utf-8"), read_buff)
    return read_buff.value.decode("utf-8")


def getCenterAddr():
    readAddr = ctypes.create_string_buffer(64)
    readPort = ctypes.create_string_buffer(64)
    res = c_get_ipaddress(b'', readAddr, readPort)
    print("获取中心服务器ip，port： ", readAddr.value, readPort.value, res)
    if res:
        return readAddr.value.decode('utf-8'), readPort.value.decode('utf-8')
    else:
        return None, None


def load_lib(libpath):
    _lib = None
    print("加载库：%s \n" % libpath)
    if sys_platform == "linux":
        _lib = _load_lib(libpath)
    elif sys_platform == "windows":
        _lib = _load_lib(libpath)
        if _lib is None:
            _lib = _load_lib(ReplaceDirector("install\\" + libpath))
    return _lib
